package uk.co.agileworks.bidpirate.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import uk.co.agileworks.bidpirate.model.Region;
import uk.co.agileworks.bidpirate.model.User;

@Component("userSession")
@Scope("session")
public final class UserSessionImpl implements UserSession {

	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = LoggerFactory.getLogger(UserSessionImpl.class);

	private User user;
	private int currentPage;

	public UserSessionImpl() {
		reset();
	}

	@Override
	public int currentPage(Integer page) {
		if (page != null) {
			currentPage = page;
		}
		return currentPage;
	}

	@Override
	public User getUser() {
		return user;
	}

	@Override
	public boolean isLoggedIn() {
		return getUser().getUsername() != null && getUser().getPassword() != null;
	}

	@Override
	public void logIn(User user) {
		this.user = user;
		LOGGER.info("Logged in user. {" + user + "}");
	}

	@Override
	public void logOut() {
		LOGGER.info("Logging out user. {" + user + "}");
		reset();
	}

	private void reset() {
		user = new User();
		user.setRegion(Region.getDefault());
		currentPage = 1;
	}

}
